<?php

namespace Admin\Controller;

class WechatMenuController extends AdminbaseController {

    public function index() {

        $count = D("wechatMenu")->count();

        $page = $this->page($count,20);

        $list = D("wechatMenu")->order('sort desc')->select();

        foreach ($list as &$menu) {
            $item = D("wechatMenuItem")->where(array('menu_id'=>$menu['menu_id']))->select();
            $menu['items'] = $item;
        }

        $this->assign("page", $page->show('Admin', null));
        $this->assign("list", $list);
        $this->display();
    }

    function add() {

        $id = I('id');

        if(IS_POST) {

            $data['menu_name'] = I('post.menuName');
            $data['sort'] = I('post.sort');
            $data['target_url'] = I('post.targetUrl');

            if(isNullOrEmpty($id)) {
                D("wechatMenu")->add($data);
            } else {
                D("wechatMenu")->where(array('menu_id'=>$id))->save($data);
            }
            $this->success('保存成功', U('wechatMenu/index'));
            exit();
        }

        if(!isNullOrEmpty($id)) {
            $menu = D("wechatMenu")->where('menu_id='.$id)->find();
            $this->assign('menu', $menu);
        }

        $this->display();

    }

    function edititem() {

        $id = I('get.id');
        $menuId = I('post.menuId');
        if(empty($id)) {
            $this->error('未找到相关信息', U('wechatMenu/index'));
            exit();
        }

        if(IS_POST) {
            $data['menu_id'] = I('post.menuId');
            $data['name'] = I('post.name');
            $data['target_url'] = I('post.targetUrl');
            $data['sort'] = I('post.sort');

            D("wechatMenuItem")->where(array('menu_item_id'=>$id))->save($data);
            $this->success('保存成功', U('wechatMenu/index'));
            exit();
        }

        $item = D("wechatMenuItem")->where('menu_item_id='.$id)->find();

        $this->assign('item', $item);

        $this->assign('menuId', $menuId);

        $menuList = D("wechatMenu")->select();

        $this->assign('menuList', $menuList);

        $this->display();

    }

    function additem() {

        if(IS_POST) {
            $data['menu_id'] = I('post.menuId');
            $data['name'] = I('post.name');
            $data['target_url'] = I('post.targetUrl');
            $data['sort'] = I('post.sort');

            D("wechatMenuItem")->add($data);
            $this->success('保存成功', U('wechatMenu/index'));
            exit();
        }

        $menuList = D("wechatMenu")->select();

        $this->assign('menuList', $menuList);

        $this->display();

    }

    function delete() {

        $id=I('get.id');

        $map['menu_id']=$id;

        D("wechatMenu")->where($map)->delete();

        $this->success('删除成功', U('wechatMenu/index'));

    }


}